package com.redhipps.hips.client.command;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.redhipps.hips.client.io.WriterCallback;
import com.redhipps.hips.client.model.Institution;
import com.redhipps.hips.client.widget.Dialogs;

// TODO Model creation command, make it common
public class CreateInstitutionCommand extends HipsCommand<Institution> {

  @Override
  public void execute(final AsyncCallback<Institution> callback) {
    final WriterCallback<Institution> writeCallback = new WriterCallback<Institution>() {
      public void onFailure(Throwable caught) {
        GWT.log("Create institution failed", caught);
        callback.onFailure(caught);
      }
      public void onSuccess(List<Institution> result) {
        GWT.log("Create institution successful", null);
        callback.onSuccess(result.get(0));
      }
    };
    final AsyncCallback<String> dialogCallback = new AsyncCallback<String>() {
      public void onFailure(Throwable caught) {
        GWT.log("Create institution failed", caught);
      }
      public void onSuccess(String result) {
        if (result == null || result.length() == 0) {
          callback.onSuccess(null);
          return;
        }
        try {
          Institution institution = new Institution();
          institution.setName(result.trim());
          createInstitution(institution, writeCallback);
        } catch (Exception e) {
          writeCallback.onFailure(e);
        }
      }
    };
    Dialogs.answer("New Institution", "Specify {name}", dialogCallback);
  }

  public void createInstitution(Institution model, WriterCallback<Institution> callback)
      throws RequestException {
    ioService().create(context(), model, callback);
  }

}
